package com.atguigu.lease.web.admin.custom.interceptor;

import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor{

    //前置拦截器的整体作用
    //统一认证入口
    //在业务逻辑执行前完成身份验证
    //避免在每个控制器方法中重复验证

    //上下文初始化
    //为整个请求处理链提供用户身份信息
    //支持后续业务逻辑获取当前用户

    //无侵入式设计
    //通过拦截器机制实现认证逻辑
    //与具体业务代码解耦
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("access_token");
        if(StringUtils.hasText(token)){
            // 如果token不为空，解析
            Claims claims = JwtUtil.parseToken(token);
            Long userId = claims.get("userId",Long.class);
            String username = claims.get("username",String.class);
            //新建登录用户类，将登录用户信息保存到线程变量中
            LoginUser loginUser = new LoginUser(userId,username);
            LoginUserContext.loginUserThreadLocal.set(loginUser);
        }

        return true;
    }

}
